var fs = require('fs');
var xml2js = require('xml2js');
var util = require('util');
var mu = require('mu2');
var express = require('express');
var http = require('http');
var https = require('https');
var path = require('path');
var MemoryStore = require('express').session.MemoryStore;
var moment = require('moment');
var config = require('./config.json');

moment.application_dateformat = config.application_dateformat;
moment.getRightDate = function(value) {
    if (value != null && value.toString().length > 0) {
        var date = null;
        if (isNaN(value)) {
            date = moment(value,'DD/MM/YYYY HH:mm:ss');
            if (!date.isValid()) {
                date = moment(value,moment.application_dateformat);
            };
        } else {
            date = moment(value);
        };
        if (date!= null && date.isValid()) {
            return date;
        } else {
            return moment();
        };
    };
    return moment();
};


// Configuring the templates path
mu.root = path.join(__dirname,config.mu_root_rel_path);

var Bookshelf = require('bookshelf');
Bookshelf.bookshelf = Bookshelf.initialize({
    client: 'sqlite',
    connection: {
        filename: path.join(__dirname, config.db_rel_path),
    },
    debug: config.use_debug,
});

var Database = require('./app/database');
Database.initialize(
    function () {
        console.log('Database successfully created!');
        if (config.use_debug) {
            Database.createTestData(function (err) { console.log('Test Data Created'); console.log(err); });
        };
    },
    function (errors) {
        console.log('Database creation failed!');
    });

var app = express();
console.log('Express initializing!');

app.configure(function () {
    app.use(express.favicon());
    if (config.use_debug) {
        app.use(express.logger('dev')); // Logs all calls to the console
    };
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.session({ secret: config.session_secret, store: new MemoryStore({ reapInterval: 60000 * 10 }) }));
    app.use(express.methodOverride());
    app.use('/console', express.static(path.join(__dirname, config.console_rel_path)));
});
if (config.use_debug) {
    app.configure('development', function () {
        app.use(express.errorHandler());
    });
};

// Configuring the routes
var Router = require('./app/router');
//console.log('router: ' + util.inspect(Router,false,null));
var UserController = require('./app/user_controller');
UserController.initialize(Router);
var ServerController = require('./app/server_controller');
ServerController.initialize(Router);
var ConfigController = require('./app/config_controller');
ConfigController.initialize(Router);
var ActionController = require('./app/action_controller');
ActionController.initialize(Router);
var MemberController = require('./app/member_controller');
MemberController.GroupUrls = config.groupUrls;
MemberController.initialize(Router);
var PlayerController = require('./app/player_controller');
PlayerController.initialize(Router);

// Static calls redirected to the webapp
app.get('/', function (req, res) {
    req.session.lastPage = req.originalUrl;
    req.session.userId = -1;
    res.redirect('/console/index.html');
});
app.get('/favicon.ico', function (req, res) {
    req.session.lastPage = req.originalUrl;
    req.session.userId = -1;
    res.redirect('/console/favicon.ico');
});

// Registered api routes
Router.register(app);
console.log('Routes registered!');

//console.log(app);
console.log('Creating HTTP server! Port: ' + config.server_port);
http.createServer(app).listen(config.server_port);
if (config.use_https) {
    var credentials = { pfx: fs.readFileSync(path.join(__dirname, config.certificate_rel_path)), passphrase: config.certificate_passphrase };
    console.log('Creating HTTPS server! Port: ' + (config.server_port + 400));
    https.createServer(credentials, app).listen(config.server_port + 400);
};
console.log('Created servers!');

console.log('Done launching');